package com.dhecp.project.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import com.bo.sellingpartnerapi.Catalogitems20201201.api.CatalogApi;
import com.bo.sellingpartnerapi.Catalogitems20201201.model.ItemSearchResults;
import com.bo.sellingpartnerapi.Catalogitemsv0.model.ListCatalogItemsResponse;
import com.bo.sellingpartnerapi.Definitionsproducttypes20200901.api.DefinitionsApi;
import com.bo.sellingpartnerapi.Definitionsproducttypes20200901.model.*;
import com.bo.sellingpartnerapi.Feeds20210630.model.Feed;
import com.bo.sellingpartnerapi.Financesv0.api.DefaultApi;
import com.bo.sellingpartnerapi.Financesv0.invoker.ApiException;
import com.bo.sellingpartnerapi.Financesv0.model.*;
import com.bo.sellingpartnerapi.Listingsitems20200901.api.ListingsApi;
import com.bo.sellingpartnerapi.Listingsitems20200901.model.ListingsItemPutRequest;
import com.bo.sellingpartnerapi.Listingsitems20200901.model.ListingsItemSubmissionResponse;
import com.bo.sellingpartnerapi.Reports20210630.api.ReportsApi;
import com.bo.sellingpartnerapi.Reports20210630.model.*;
import com.dhecp.common.config.Global;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.core.utils.DateUtils;
import com.dhecp.project.api.client.model.SellerSecretsVO;
import com.dhecp.project.api.domain.Address;
import com.dhecp.project.api.domain.AmazonShop;
import com.dhecp.project.api.domain.ApiResponse;
import com.dhecp.project.api.enums.MarketplaceEnum;
import com.dhecp.project.api.enums.RegionEnum;
import com.dhecp.project.api.mapper.AmazonShopMapper;
import com.dhecp.project.api.service.ApiAmazonService;
import com.dhecp.project.api.service.ApiLogService;
import com.dhecp.project.api.util.ApiConfig;
import com.dhecp.project.api.util.Helper;
import com.squareup.okhttp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.threeten.bp.OffsetDateTime;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;

/**
 * @ClassName ApiFinancesTask
 * @Description TODO
 * @Author alula
 * @Date 2022-09-26 9:33
 */
@Component("apiFinancesTask")
public class ApiFinancesTask {

    private static final Logger logger = LoggerFactory.getLogger(ApiFinancesTask.class);
    //亚马逊系统名称
    private static final String AMAZON_SYSTEM_NAME = "Amazon";

    @Autowired
    private ApiLogService apiLogService;

    @Autowired
    private ApiAmazonService apiAmazonService;

    @Autowired
    private AmazonShopMapper amazonShopMapper;

    /**
     * 定时获取亚马逊订单信息(3:00运行)
     */
    public void financialEventGroups111() throws ApiException {
        try {
//            AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid("6ffd99eb-2be6-4dba-9487-9c5242adba16");
            AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid("67a73c28-d0d7-47d2-a474-c280a55233d6");
            Address address = new Address();
            SellerSecretsVO secretsVO = new SellerSecretsVO();
            getAmazonShop(amazonShop, address, secretsVO);
//        DefaultApi api = Helper.buildApi(secretsVO, DefaultApi.class);
            Calendar calendar = new GregorianCalendar();
            calendar.set(Calendar.YEAR,2023);
            calendar.set(Calendar.MONTH,8);
            calendar.set(Calendar.DATE,1);
            calendar.set(Calendar.HOUR_OF_DAY,00);
            calendar.set(Calendar.MINUTE,00);
            calendar.set(Calendar.SECOND,00);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date startTime = calendar.getTime();

            String startTimeStr = DateUtils.convertDateToTDate(startTime);
            Calendar calendar1 = new GregorianCalendar();
            calendar1.set(Calendar.YEAR,2023);
            calendar1.set(Calendar.MONTH,8);
            calendar1.set(Calendar.DATE,8);
            calendar1.set(Calendar.MINUTE,00);
            calendar1.set(Calendar.SECOND,00);
            Date endTime = calendar1.getTime();
            String endTimeStr = DateUtils.convertDateToTDate(endTime);

            //获取区域对应的端点枚举，取不到直接跳转过
            RegionEnum regionEnum = RegionEnum.from(amazonShop.getRegionCode().toUpperCase());

            AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                    .accessKeyId(ApiConfig.getAmazonAwsAccessKey())
                    .secretKey(ApiConfig.getAmazonAwsAccessSecret())
                    .region(regionEnum.getAwsRegion())
                    .build();
            AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                    .roleArn(ApiConfig.getAmazonRoleArn())
                    .roleSessionName(ApiConfig.getAmazonRoleSessionName())
                    .build();
            LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                    .clientId(ApiConfig.getAmazonLwaClientKey())
                    .clientSecret(ApiConfig.getAmazonLwaClientSecret())
                    .refreshToken(amazonShop.getRefreshToken())
                    .endpoint(ApiConfig.getAmazonLwaEndpoint())
                    .build();

            ReportsApi api = new ReportsApi.Builder()
                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                    .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                    .endpoint(regionEnum.getServiceUrl())
                    .build();
            List<String> marketplaceIdList =  new ArrayList<>();
            if(!StringUtils.isEmpty(amazonShop.getMarketplaceIds())) {
                String marketplaceIds = amazonShop.getMarketplaceIds();
                String[] marketplaceIdArray = marketplaceIds.split(",");
                marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
            }
            CreateReportSpecification body = new CreateReportSpecification();
//            body.setReportType("GET_REFERRAL_FEE_PREVIEW_REPORT");
//            body.setReportType("GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2");
            body.setReportType("GET_DATE_RANGE_FINANCIAL_TRANSACTION_DATA");
            body.setMarketplaceIds(marketplaceIdList);
//            body.setDataStartTime(OffsetDateTime.parse(startTimeStr));
//            body.setDataEndTime(OffsetDateTime.parse(endTimeStr));
//            ReportOptions reportOptions = new ReportOptions();
//            reportOptions.put("custom", "true");
//            body.setReportOptions(reportOptions);
            CreateReportResponse reportResponse =  null;
            reportResponse = api.createReport(body);
            String reportId = reportResponse.getReportId();
            String reportDocumentId = "";
            Report report = null;
            Report.ProcessingStatusEnum processingStatus = null;
            while (true) {
                report = api.getReport(reportId);
                processingStatus = report.getProcessingStatus();
                if (Feed.ProcessingStatusEnum.DONE.getValue().equals(processingStatus.getValue())
                        || Feed.ProcessingStatusEnum.CANCELLED.getValue().equals(processingStatus.getValue())
                        || Feed.ProcessingStatusEnum.FATAL.getValue().equals(processingStatus.getValue())) {
                    if (report != null) {
                        reportDocumentId = report.getReportDocumentId();
                    }
                    break;
                } else {
                    Thread.sleep(10000L);
                    continue;
                }
            }
            if (report != null) {
                if (!StringUtils.isEmpty(reportDocumentId)) {
                    ReportDocument reportDocument = api.getReportDocument(reportDocumentId);
                    if (reportDocument != null) {
                        String compressionAlgorithm = (reportDocument.getCompressionAlgorithm() == null ? "" : reportDocument.getCompressionAlgorithm().toString());
                        OkHttpClient httpclient = new OkHttpClient();
                        Request request = new Request.Builder()
                                .url(reportDocument.getUrl())
                                .get()
                                .build();

                        Response httpResponse = httpclient.newCall(request).execute();

                        try (ResponseBody responseBody = httpResponse.body()) {
                            MediaType mediaType = MediaType.parse(httpResponse.header("Content-Type"));
                            Charset charset = mediaType.charset();

                            Closeable closeThis = null;
                            InputStream inputStream = responseBody.byteStream();
                            closeThis = inputStream;
                            if ("GZIP".equals(compressionAlgorithm)) {
                                inputStream = new GZIPInputStream(inputStream);
                                closeThis = inputStream;
                            }
//                                if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                            closeThis = inputStreamReader;
                            BufferedReader reader = new BufferedReader(inputStreamReader);
                            closeThis = reader;
                            StringBuilder stringBuilder = new StringBuilder();
                            String line;
                            do {
                                line = reader.readLine();
                                if (line != null) {
                                    stringBuilder.append(line);
                                    stringBuilder.append("\n");
                                }
                            } while (line != null);
                            String filePath = Global.getProfile() + "/amazonreport/order/" + simpleDateFormat.format(new Date()).replace("-", "");
                            String fileName = "order_report_" + amazonShop.getGuid() + ".cvs";
                            File file = new File(filePath);
                            if (!file.exists()) {
                                file.mkdirs();
                            }
                            File reportFile = new File(filePath + "/" + fileName);
                            if (!reportFile.exists()) {
                                reportFile.createNewFile();
                            }
                            OutputStream outputStream = new FileOutputStream(reportFile);
                            outputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
                            outputStream.close();
                            BufferedReader csvBufferedReader = null;
                            String reportLine = "";
                            String separator = "\t";
                            InputStreamReader csvInputStreamReader = new InputStreamReader(new FileInputStream(filePath + "/" + fileName), StandardCharsets.UTF_8);
                            csvBufferedReader = new BufferedReader(csvInputStreamReader);
                            String title = csvBufferedReader.readLine();

                            String[] titleSplit = title.split(separator);
                            while ((reportLine = csvBufferedReader.readLine()) != null) {
                                if (!StringUtils.isEmpty(reportLine)) {
                                    //内容数组
                                    String[] reportArray = reportLine.split(separator);
                                    //判断内容和标题的size
                                    if ((reportArray.length) < titleSplit.length) {
                                        int len = titleSplit.length - reportArray.length;
                                        reportArray = Arrays.copyOf(reportArray, reportArray.length + len);
                                    }
                                }
                            }
//                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e = e;
        }
    }

    /**
     * 定时获取亚马逊订单信息(3:00运行)
     */
    public void financialEventGroups1() throws ApiException {
            try {
//                AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid("6ffd99eb-2be6-4dba-9487-9c5242adba16");
                AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid("c7af2ec6-5c74-4b9e-9335-2acaaf2252cc");
                Address address = new Address();
                SellerSecretsVO secretsVO = new SellerSecretsVO();
                getAmazonShop(amazonShop, address, secretsVO);
//        DefaultApi api = Helper.buildApi(secretsVO, DefaultApi.class);
                Calendar calendar = new GregorianCalendar();
                calendar.set(Calendar.YEAR,2023);
                calendar.set(Calendar.MONTH,5);
                calendar.set(Calendar.DATE,1);
                calendar.set(Calendar.HOUR_OF_DAY,00);
                calendar.set(Calendar.MINUTE,00);
                calendar.set(Calendar.SECOND,00);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date startTime = calendar.getTime();

                String startTimeStr = DateUtils.convertDateToTDate(startTime);
                Calendar calendar1 = new GregorianCalendar();
                calendar1.set(Calendar.YEAR,2023);
                calendar1.set(Calendar.MONTH,5);
                calendar1.set(Calendar.DATE,30);
                calendar1.set(Calendar.HOUR_OF_DAY,23);
                calendar1.set(Calendar.MINUTE,59);
                calendar1.set(Calendar.SECOND,59);
                Date endTime = calendar1.getTime();
                String endTimeStr = DateUtils.convertDateToTDate(endTime);

                //获取区域对应的端点枚举，取不到直接跳转过
                RegionEnum regionEnum = RegionEnum.from(amazonShop.getRegionCode().toUpperCase());

                AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                        .accessKeyId(ApiConfig.getAmazonAwsAccessKey())
                        .secretKey(ApiConfig.getAmazonAwsAccessSecret())
                        .region(regionEnum.getAwsRegion())
                        .build();
                AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                        .roleArn(ApiConfig.getAmazonRoleArn())
                        .roleSessionName(ApiConfig.getAmazonRoleSessionName())
                        .build();
                LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                        .clientId(ApiConfig.getAmazonLwaClientKey())
                        .clientSecret(ApiConfig.getAmazonLwaClientSecret())
                        .refreshToken(amazonShop.getRefreshToken())
                        .endpoint(ApiConfig.getAmazonLwaEndpoint())
                        .build();

                DefaultApi api = new DefaultApi.Builder()
                        .awsAuthenticationCredentials(awsAuthenticationCredentials)
                        .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                        .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                        .endpoint(regionEnum.getServiceUrl())
                        .build();
                ListFinancialEventGroupsResponse listFinancialEventGroupsResponse =
                        api.listFinancialEventGroups(
                                null, OffsetDateTime.parse(endTimeStr),OffsetDateTime.parse(startTimeStr),null);
                listFinancialEventGroupsResponse = listFinancialEventGroupsResponse;
                ListFinancialEventGroupsPayload listFinancialEventGroupsPayload = listFinancialEventGroupsResponse.getPayload();
                FinancialEventGroupList financialEventGroupList = listFinancialEventGroupsPayload.getFinancialEventGroupList();
                for (FinancialEventGroup financialEventGroup : financialEventGroupList){
                    boolean isTrue = true;
                    String nextToken = null;
                    while (isTrue){
                        ListFinancialEventsResponse listFinancialEventsResponse =
                                api.listFinancialEventsByGroupId( financialEventGroupList.get(0).getFinancialEventGroupId(), null,nextToken);
                        ListFinancialEventsPayload payload = listFinancialEventsResponse.getPayload();
                        payload = payload;
                        FinancialEvents financialEvents = payload.getFinancialEvents();
                        DebtRecoveryEventList debtRecoveryEventList = financialEvents.getDebtRecoveryEventList();
                        if (payload.getNextToken() != null){
                            nextToken = payload.getNextToken();
                        }else {
                            isTrue = false;
                        }
                    }
                }
            }catch (Exception e){
                e = e;
            }
    }

    /**
     * createReportSchedule
     */
    public void createReportSchedule() throws ApiException {
        try {
            AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid("6ffd99eb-2be6-4dba-9487-9c5242adba16");
            Address address = new Address();
            SellerSecretsVO secretsVO = new SellerSecretsVO();
            getAmazonShop(amazonShop, address, secretsVO);
//        DefaultApi api = Helper.buildApi(secretsVO, DefaultApi.class);
            Calendar calendar = new GregorianCalendar();
            calendar.set(Calendar.YEAR,2023);
            calendar.set(Calendar.MONTH,6);
            calendar.set(Calendar.DATE,1);
            calendar.set(Calendar.HOUR_OF_DAY,00);
            calendar.set(Calendar.MINUTE,00);
            calendar.set(Calendar.SECOND,00);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date startTime = calendar.getTime();

            String startTimeStr = DateUtils.convertDateToTDate(startTime);
            Calendar calendar1 = new GregorianCalendar();
            calendar1.set(Calendar.YEAR,2023);
            calendar1.set(Calendar.MONTH,6);
            calendar1.set(Calendar.DATE,31);
            calendar1.set(Calendar.MINUTE,00);
            calendar1.set(Calendar.SECOND,00);
            Date endTime = calendar1.getTime();
            String endTimeStr = DateUtils.convertDateToTDate(endTime);

            //获取区域对应的端点枚举，取不到直接跳转过
            RegionEnum regionEnum = RegionEnum.from(amazonShop.getRegionCode().toUpperCase());

            AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                    .accessKeyId(ApiConfig.getAmazonAwsAccessKey())
                    .secretKey(ApiConfig.getAmazonAwsAccessSecret())
                    .region(regionEnum.getAwsRegion())
                    .build();
            AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                    .roleArn(ApiConfig.getAmazonRoleArn())
                    .roleSessionName(ApiConfig.getAmazonRoleSessionName())
                    .build();
            LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                    .clientId(ApiConfig.getAmazonLwaClientKey())
                    .clientSecret(ApiConfig.getAmazonLwaClientSecret())
                    .refreshToken(amazonShop.getRefreshToken())
                    .endpoint(ApiConfig.getAmazonLwaEndpoint())
                    .build();

            ReportsApi api = new ReportsApi.Builder()
                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                    .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                    .endpoint(regionEnum.getServiceUrl())
                    .build();
            List<String> marketplaceIdList =  new ArrayList<>();
            if(!StringUtils.isEmpty(amazonShop.getMarketplaceIds())) {
                String marketplaceIds = amazonShop.getMarketplaceIds();
                String[] marketplaceIdArray = marketplaceIds.split(",");
                marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
            }
            CreateReportScheduleSpecification body = new CreateReportScheduleSpecification();
//            body.setReportType("GET_REFERRAL_FEE_PREVIEW_REPORT");
//            body.setReportType("GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2");
            body.setReportType("GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL");
//            body.setReportType("GET_DATE_RANGE_FINANCIAL_TRANSACTION_DATA");
            body.setMarketplaceIds(marketplaceIdList);
            body.setPeriod(CreateReportScheduleSpecification.PeriodEnum.PT5M);
//            ReportOptions reportOptions = new ReportOptions();
//            reportOptions.put("custom", "true");
//            body.setReportOptions(reportOptions);
            CreateReportScheduleResponse reportResponse =  null;
            reportResponse = api.createReportSchedule(body);
            String reportDocumentId = reportResponse.getReportScheduleId();
            if (reportDocumentId != null) {
                if (!StringUtils.isEmpty(reportDocumentId)) {
                    ReportDocument reportDocument = api.getReportDocument(reportDocumentId);
                    if (reportDocument != null) {
                        String compressionAlgorithm = (reportDocument.getCompressionAlgorithm() == null ? "" : reportDocument.getCompressionAlgorithm().toString());
                        OkHttpClient httpclient = new OkHttpClient();
                        Request request = new Request.Builder()
                                .url(reportDocument.getUrl())
                                .get()
                                .build();

                        Response httpResponse = httpclient.newCall(request).execute();

                        try (ResponseBody responseBody = httpResponse.body()) {
                            MediaType mediaType = MediaType.parse(httpResponse.header("Content-Type"));
                            Charset charset = mediaType.charset();

                            Closeable closeThis = null;
                                InputStream inputStream = responseBody.byteStream();
                                closeThis = inputStream;
                                if ("GZIP".equals(compressionAlgorithm)) {
                                    inputStream = new GZIPInputStream(inputStream);
                                    closeThis = inputStream;
                                }
//                                if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                                    closeThis = inputStreamReader;
                                    BufferedReader reader = new BufferedReader(inputStreamReader);
                                    closeThis = reader;
                                    StringBuilder stringBuilder = new StringBuilder();
                                    String line;
                                    do {
                                        line = reader.readLine();
                                        if (line != null) {
                                            stringBuilder.append(line);
                                            stringBuilder.append("\n");
                                        }
                                    } while (line != null);
                                    String filePath = Global.getProfile() + "/amazonreport/order/" + simpleDateFormat.format(new Date()).replace("-", "");
                                    String fileName = "order_report_" + amazonShop.getGuid() + ".cvs";
                                    File file = new File(filePath);
                                    if (!file.exists()) {
                                        file.mkdirs();
                                    }
                                    File reportFile = new File(filePath + "/" + fileName);
                                    if (!reportFile.exists()) {
                                        reportFile.createNewFile();
                                    }
                                    OutputStream outputStream = new FileOutputStream(reportFile);
                                    outputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
                                    outputStream.close();
                                    BufferedReader csvBufferedReader = null;
                                    String reportLine = "";
                                    String separator = "\t";
                                    InputStreamReader csvInputStreamReader = new InputStreamReader(new FileInputStream(filePath + "/" + fileName), StandardCharsets.UTF_8);
                                    csvBufferedReader = new BufferedReader(csvInputStreamReader);
                                    String title = csvBufferedReader.readLine();

                                    String[] titleSplit = title.split(separator);
                                    while ((reportLine = csvBufferedReader.readLine()) != null) {
                                        if (!StringUtils.isEmpty(reportLine)) {
                                            //内容数组
                                            String[] reportArray = reportLine.split(separator);
                                            //判断内容和标题的size
                                            if ((reportArray.length) < titleSplit.length) {
                                                int len = titleSplit.length - reportArray.length;
                                                reportArray = Arrays.copyOf(reportArray, reportArray.length + len);
                                            }
                                        }
                                }
//                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e = e;
        }
    }
    /**
     * 定时获取亚马逊订单信息(3:00运行)
     */
    public void financialEventGroups2() throws ApiException {
        try {
            AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid("6ffd99eb-2be6-4dba-9487-9c5242adba16");
//            AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid("a6f23e3f-fb05-4059-9cec-92b361bad2a7");
            Address address = new Address();
            SellerSecretsVO secretsVO = new SellerSecretsVO();
            getAmazonShop(amazonShop, address, secretsVO);
//        DefaultApi api = Helper.buildApi(secretsVO, DefaultApi.class);
            Calendar calendar = new GregorianCalendar();
            calendar.set(Calendar.YEAR, 2022);
            calendar.set(Calendar.MONTH, 1);
            calendar.set(Calendar.DATE, 1);
            calendar.set(Calendar.MINUTE, 00);
            calendar.set(Calendar.SECOND, 00);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date startTime = calendar.getTime();

            String startTimeStr = DateUtils.convertDateToTDate(startTime);
            Calendar calendar1 = new GregorianCalendar();
            calendar1.set(Calendar.YEAR, 2022);
            calendar1.set(Calendar.MONTH, 2);
            calendar1.set(Calendar.DATE, 9);
            calendar.set(Calendar.MINUTE, 00);
            calendar.set(Calendar.SECOND, 00);
            Date endTime = calendar1.getTime();
            String endTimeStr = DateUtils.convertDateToTDate(endTime);

            //获取区域对应的端点枚举，取不到直接跳转过
            RegionEnum regionEnum = RegionEnum.from(amazonShop.getRegionCode().toUpperCase());

            AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                    .accessKeyId(ApiConfig.getAmazonAwsAccessKey())
                    .secretKey(ApiConfig.getAmazonAwsAccessSecret())
                    .region(regionEnum.getAwsRegion())
                    .build();
            AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                    .roleArn(ApiConfig.getAmazonRoleArn())
                    .roleSessionName(ApiConfig.getAmazonRoleSessionName())
                    .build();
            LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                    .clientId(ApiConfig.getAmazonLwaClientKey())
                    .clientSecret(ApiConfig.getAmazonLwaClientSecret())
                    .refreshToken(amazonShop.getRefreshToken())
                    .endpoint(ApiConfig.getAmazonLwaEndpoint())
                    .build();

            ReportsApi api = new ReportsApi.Builder()
                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                    .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                    .endpoint(regionEnum.getServiceUrl())
                    .build();
            List<String> marketplaceIdList = new ArrayList<>();
            if (!StringUtils.isEmpty(amazonShop.getMarketplaceIds())) {
                String marketplaceIds = amazonShop.getMarketplaceIds();
                String[] marketplaceIdArray = marketplaceIds.split(",");
                marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
            }
            CreateReportSpecification body = new CreateReportSpecification();
//            body.setReportType("GET_REFERRAL_FEE_PREVIEW_REPORT");
//            body.setReportType("GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2");
            body.setMarketplaceIds(marketplaceIdList);
//            body.setDataStartTime(OffsetDateTime.parse(startTimeStr));
//            body.setDataEndTime(OffsetDateTime.parse(endTimeStr));
            CreateReportResponse reportResponse = null;
            List<String> reportTypes = new ArrayList<>();
            reportTypes.add("GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2");// 获取的是所有结算中的下载内容  问题1：只能保留90天报告那就不符合之前的全年的数据
//            reportTypes.add("GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE");// 获取交易一览中的下载类容
//            reportTypes.add("GET_V2_SETTLEMENT_REPORT_DATA_XML");// 获取的是所有结算中的下载内容  问题1：只能保留90天报告那就不符合之前的全年的数据
//            reportTypes.add("GET_DATE_RANGE_FINANCIAL_TRANSACTION_DATA");//获取的是日期范围报告可以下载的报告
            GetReportsResponse reports = api.getReports(reportTypes, null, marketplaceIdList,
                    100, null, null, null);
            ReportList reports1 = reports.getReports();
//            for (Report report : reports1) {
                ReportDocument reportDocument = api.getReportDocument(reports1.get(0).getReportDocumentId());
                if (reportDocument != null) {
                    String compressionAlgorithm = (reportDocument.getCompressionAlgorithm() == null ? "" : reportDocument.getCompressionAlgorithm().toString());
                    OkHttpClient httpclient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(reportDocument.getUrl())
                            .get()
                            .build();

                    Response httpResponse = httpclient.newCall(request).execute();

                    try (ResponseBody responseBody = httpResponse.body()) {
                        MediaType mediaType = MediaType.parse(httpResponse.header("Content-Type"));
                        Charset charset = mediaType.charset();

                        Closeable closeThis = null;
                        InputStream inputStream = responseBody.byteStream();
                        closeThis = inputStream;
                        if ("GZIP".equals(compressionAlgorithm)) {
                            inputStream = new GZIPInputStream(inputStream);
                            closeThis = inputStream;
                        }
//                                if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
                        closeThis = inputStreamReader;
                        BufferedReader reader = new BufferedReader(inputStreamReader);
                        closeThis = reader;
                        StringBuilder stringBuilder = new StringBuilder();
                        String line;
                        do {
                            line = reader.readLine();
                            if (line != null) {
                                stringBuilder.append(line);
                                stringBuilder.append("\n");
                            }
                        } while (line != null);
                        String filePath = Global.getProfile() + "/amazonreport/order1/" + simpleDateFormat.format(new Date()).replace("-", "");
                        String fileName = "order_report_" + amazonShop.getGuid() + ".xlsx";
                        File file = new File(filePath);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        File reportFile = new File(filePath + "/" + fileName);
                        if (!reportFile.exists()) {
                            reportFile.createNewFile();
                        }
                        OutputStream outputStream = new FileOutputStream(reportFile);
                        outputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
                        outputStream.close();
                        BufferedReader csvBufferedReader = null;
                        String reportLine = "";
                        String separator = "\t";
                        InputStreamReader csvInputStreamReader = new InputStreamReader(new FileInputStream(filePath + "/" + fileName), StandardCharsets.UTF_8);
                        csvBufferedReader = new BufferedReader(csvInputStreamReader);
                        String title = csvBufferedReader.readLine();

                        String[] titleSplit = title.split(separator);
                        while ((reportLine = csvBufferedReader.readLine()) != null) {
                            if (!StringUtils.isEmpty(reportLine)) {
                                //内容数组
                                String[] reportArray = reportLine.split(separator);
                                //判断内容和标题的size
                                if ((reportArray.length) < titleSplit.length) {
                                    int len = titleSplit.length - reportArray.length;
                                    reportArray = Arrays.copyOf(reportArray, reportArray.length + len);
                                }
                            }
                        }
//                            }
//                    }
                }
            }
        }catch (Exception e){
            e = e;
        }
    }

        private void getAmazonShop(AmazonShop amazonShop,Address address,SellerSecretsVO secretsVO) {
        //查询网店信息
        if (amazonShop != null) {
            address.setName(amazonShop.getName());
            address.setAddressLine1(amazonShop.getAddressLine1());
            address.setAddressLine2(amazonShop.getAddressLine2());
            address.setDistrictOrCounty(amazonShop.getDistrictOrCounty());
            address.setCity(amazonShop.getCity());
            address.setStateOrProvinceCode(amazonShop.getStateOrProvinceCode());
//            address.setCountryCode(amazonShop.getCountryCode());
            address.setCountryCode("CN");
            address.setPostalCode(amazonShop.getPostalCode());

            secretsVO.setAWSAuthenticationCredentials_AK(ApiConfig.getAmazonAwsAccessKey());
            secretsVO.setAWSAuthenticationCredentials_SK(ApiConfig.getAmazonAwsAccessSecret());
            secretsVO.setAWSAuthenticationCredentialsProvider_roleArn(ApiConfig.getAmazonRoleArn());
            secretsVO.setlWAAuthorizationCredentials_clientid(ApiConfig.getAmazonLwaClientKey());
            secretsVO.setLWAAuthorizationCredentials_clientSecret(ApiConfig.getAmazonLwaClientSecret());
            secretsVO.setSeller_id(amazonShop.getSellerId());
            secretsVO.setLWAAuthorizationCredentials_refreshToken(amazonShop.getRefreshToken());

            if ("欧洲".equals(amazonShop.getRegionName())) {
                secretsVO.setMarketPlace(MarketplaceEnum.EUROPE.getCode());
            } else if ("北美".equals(amazonShop.getRegionName())) {
                secretsVO.setMarketPlace(MarketplaceEnum.NORTH.getCode());
            } else if ("远东".equals(amazonShop.getRegionName())) {
                secretsVO.setMarketPlace(MarketplaceEnum.ASIA.getCode());
            } else {
//                throw new RuntimeException(amazonShop.getShopName() + "地区名称不合规!");
            }
        }
    }

    /**
     * TODO 自动生成商品
     */
    public void financialEventGroups() throws ApiException {
        try {
            AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid("6ffd99eb-2be6-4dba-9487-9c5242adba16");
            Address address = new Address();
            SellerSecretsVO secretsVO = new SellerSecretsVO();
            getAmazonShop(amazonShop, address, secretsVO);
            //获取区域对应的端点枚举，取不到直接跳转过
            RegionEnum regionEnum = RegionEnum.from(amazonShop.getRegionCode().toUpperCase());

            AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                    .accessKeyId(ApiConfig.getAmazonAwsAccessKey())
                    .secretKey(ApiConfig.getAmazonAwsAccessSecret())
                    .region(regionEnum.getAwsRegion())
                    .build();
            AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                    .roleArn(ApiConfig.getAmazonRoleArn())
                    .roleSessionName(ApiConfig.getAmazonRoleSessionName())
                    .build();
            LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                    .clientId(ApiConfig.getAmazonLwaClientKey())
                    .clientSecret(ApiConfig.getAmazonLwaClientSecret())
                    .refreshToken(amazonShop.getRefreshToken())
                    .endpoint(ApiConfig.getAmazonLwaEndpoint())
                    .build();

            CatalogApi api = new CatalogApi.Builder()
                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                    .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                    .endpoint(regionEnum.getServiceUrl())
                    .build();
            DefinitionsApi definitionsApi = new DefinitionsApi.Builder()
                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                    .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                    .endpoint(regionEnum.getServiceUrl())
                    .build();
            List<String> marketplaceIdList =  new ArrayList<>();
            if(!StringUtils.isEmpty(amazonShop.getMarketplaceIds())) {
                String marketplaceIds = amazonShop.getMarketplaceIds();
                String[] marketplaceIdArray = marketplaceIds.split(",");
                marketplaceIdList = new ArrayList<>(Arrays.asList(marketplaceIdArray));
            }
            List<String> keywords = new ArrayList<>();
            keywords.add("Potassium-Based Fertilisers");
//            List<String> keywords1 = new ArrayList<>();
//            keywords1.add("EZIOLY");
            List<String> includedData  = new ArrayList<>();
            includedData.add("productTypes");

            try {
//                ItemSearchResults result = api.searchCatalogItems(
//                        keywords, marketplaceIdList, includedData,null,
//                        null,20,"", null, null);
                ProductTypeList productTypeList = definitionsApi.searchDefinitionsProductTypes(marketplaceIdList, null);
                List<ProductType> productTypeList1 = productTypeList.getProductTypes();
                for (ProductType productType : productTypeList1){
                    if (productType.getName().equals("CABLE TIE")){
                        System.out.println();
                    }
                }
                ProductTypeDefinition fertilizer = definitionsApi.getDefinitionsProductType("FERTILIZER"
                        , marketplaceIdList, amazonShop.getSellerId(), null, null, null, null);
                if (fertilizer!=null){
                    SchemaLink metaSchema = fertilizer.getMetaSchema();
                    SchemaLink schema = fertilizer.getSchema();
                    SchemaLinkLink link = schema.getLink();
                    String resource = link.getResource();
                    schema = schema;
                }
                System.out.println("");

            } catch (Exception e) {
                System.err.println("Exception when calling CatalogApi#listCatalogItems");
                e.printStackTrace();
            }


            ListingsApi listingsApi = new ListingsApi.Builder()
                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                    .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                    .endpoint(regionEnum.getServiceUrl())
                    .build();

            ListingsItemPutRequest body = new ListingsItemPutRequest();
            body.setProductType("CABLE TIE");
            body.setRequirements(ListingsItemPutRequest.RequirementsEnum.LISTING);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("brand","SICAILU");
            List<String>  bullet_pointList = new ArrayList<>();
            bullet_pointList.add("【Package Includes】Comes with 200pcs black cable clips, very easy to install, make your home look more classy and clean.");
//            bullet_pointList.add("【Convenient to Use】The cable clips is a kind of portable self-adhesive clips. The self-adhesive pads adhere to any smooth and clean surfaces of desks, walls, base boards, cabinets, wood, etc.");
//            bullet_pointList.add("【High Quality】Made of high quality and durable plastic material, small in size and space-saving, disassemble easily and without any residues.");
//            bullet_pointList.add("【Easy to Use】No need to punch a hole or attach any screws, peel and stick your self-adhesive cable clip anywhere.");
//            bullet_pointList.add("【Wide Application】Worked great for cable management, fixed various wires, network cable, TV-coax cable, USB cords and cell phone chargers. Can be applied for plastic plates, glass, iron, wood furniture, porcelain, etc.");
//            bullet_pointList.add("Cable Management Clip Cable Clip Cable Holder Wire Clip Wire Clamp Self-Adhesive Cable Ties Cable Organisers ");
//            params.put("contains_liquid_contents",bullet_pointList);
//            params.put("country_of_origin","China");
//            params.put("included_components","False");
//            params.put("ingredients","False");
//            params.put("is_expiration_dated_product","False");
//            params.put("item_form","6.99");
//            params.put("manufacturer","SICAILU");
//            params.put("item_name","200 PCS Cable Clips, Self Adhesive Cable Management Cable Organizer Wire Cord Tie Holder for Car Office and Home");
//            params.put("number_of_items","1");
//            params.put("part_number","LJH-001");
//            params.put("product_description","200 PCS Cable Clips, Self Adhesive Cable Management Cable Organizer -001");
//            params.put("recommended_browse_nodes","1258745511");
//            params.put("supplier_declared_dg_hz_regulation","");
            body.setAttributes(params);
            ListingsItemSubmissionResponse listingsItemSubmissionResponse =
                    listingsApi.putListingsItem(amazonShop.getSellerId(), "AKSJSDWWS-FXZ1", marketplaceIdList, body, null);
            listingsItemSubmissionResponse = listingsItemSubmissionResponse;
        } catch (Exception e){
            System.out.println();
        }

    }
}
